<?php
require_once('iReader.php');
require_once('File Classes/rFactorFile.php');
require_once('Result.php');
require_once('../Series.php');
/**
 * Liest die von dem Spiel erstellen Ergebnisdaten aus.
 * Diese werden dann weitergereicht, um verarbeitet zu werden.
 *
 * Für: rFactor
 *
 * @author Timo
 */
class rFactorReader implements iReader
{
    private $result    = array();
    private $series    = null;
    private $game_file = null;
    /*
     * Konstruktor: Mit Dateinamen werden direkt Ergebnisse aus einer Datei eingelesen.
     */
    function __construct($series, $filepath = '')
    {
        if($series instanceof Series)
        {
            $this->series = $series;
        }
        
        $this->ReadFromFile($filepath);
    }

    public function ReadFromFile($filename)
    {
        if(is_string($filename) && $filename != '')
        {
            $temp_file       = new rFactorFile($filename);
            $this->game_file = $temp_file->GetContents();
        }
        else
        {
            echo 'Error: "' . $filename . '" is not a string or empty';
        }
        
        require_once('../Database/Database.php');
        foreach($this->game_file->RaceResults->Race->Driver as $driver)
        {
            $temp_result = new Result();
        
            $db = new Database();
            $db->Connect();
            
            $driver_ids = $db->SelectColumns($this->series->GetShortcut() . '_drivers', 'ID_Driver, Team_ID', 'Name = ' . $driver->Name);
            $db->Disconnect();
            if($driver_ids)
            {
                $temp_result->SetDriverID($driver_ids[0]->ID_Driver);
    
                $temp_result->SetStatus($driver->FinishStatus);
                $temp_result->SetStartPosition($driver->GridPos);
                $temp_result->SetPosition($driver->Position);
                $temp_result->SetPitstops($driver->Pitstops);
            
                $this->result[] = $temp_result;
            }
        }
    }
    
    public function ReadFromDatabase() 
    {
        require_once('../Database/Database.php');
        
        //$db = new Database();
        // TODO: Lesen aus Datenbank..
    }

    /*
     * Liefert Array aus Objekten zurück -> Fahrer, Teams
     */
    public function GetData()
    {
        return $this->result;
    }
}
?>